package cn.dxs.adt.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.dxs.adt.R;

public class FloatingViewService extends Service implements WindowChangeDetectingService.AccessibilityServiceListener {

    private WindowManager mWm;
    private static LinearLayout root;
    private TextView mTv_packageName;
    private TextView mTv_activityName;

    @Override
    public void onCreate() {
        super.onCreate();
        WindowChangeDetectingService.setListener(this);
        this.mWm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        b();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mWm.removeView(root);
        stopSelf();
    }

    private void setText(String packageName, String activityName) {
        this.mTv_packageName.setText(packageName);
        this.mTv_activityName.setText(activityName);
    }

    private void b() {
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        root = (LinearLayout) LayoutInflater.from(getApplication()).inflate(R.layout.layout_floating_view, null);
        this.mTv_packageName = (TextView) root.findViewById(R.id.package_name);
        this.mTv_activityName = (TextView) root.findViewById(R.id.activity_name);
        layoutParams.type = Build.VERSION.SDK_INT >= 26 ? 2038 : 2003;
        layoutParams.format = 1;
        layoutParams.flags = 24;
        layoutParams.gravity = 51;
        layoutParams.x = 0;
        layoutParams.y = 0;
        layoutParams.width = -2;
        layoutParams.height = -2;
        this.mWm.addView(root, layoutParams);
    }

    @Override
    public void windowChange(String packageName, String activityName) {
        setText(packageName, activityName);
    }

    /**
     * 开/关窗口视图（隐藏/显示窗口视图）
     */
    public static void switchFloatingView() {
        if (root == null) {
            return;
        }
        if (root.getVisibility() == View.VISIBLE) {
            root.setVisibility(View.GONE);
        } else {
            root.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 获取窗口视图的显示状态
     */
    public static boolean getFloatingViewShowState() {
        if (root == null || root.getVisibility() != View.VISIBLE) {
            return false;
        }
        return true;
    }
}